﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ServeNHL.Models;


namespace ServeNHL.Controllers
{
    public class UserController : Controller
    {
        // GET: User

        public ActionResult AccountManage(string errmsg)
        {
            ViewBag.error = errmsg;
            var user = new UserViewModel();
           
            //redirect to login if not signed in
            if (Session["userid"] == null)
            {
                ViewBag.Message = "Please sign in";
                return RedirectToAction("login", "Security", new {msg = "Please login to continue" });
            }
            //check if signed in 
            string userID = Session["userid"].ToString();
           
            
            user = user.getUser(userID);
            //getEvents();
            return View(user);
            
           
            

            // return View("AccountManage");
        }

        //return user info Probably a view model
        /* public ActionResult getUser (int id)
         {
             var user = new UserViewModel();

             user.getUser(id);
             return View(user);
         }
         */
        //public ActionResult getevent ()

        public ActionResult Save()
        {
            var user = new UserViewModel();
            user.user.SaveUser(user);// 
            return View("Index");

        }
        public ActionResult AddFamily()
        {
            //redirect to login if not signed in
            if (Session["userid"] == null)
            {
               
                return RedirectToAction("login", "Security", new { msg = "Please login to continue" });
            }
            var fam = new List<UserViewModel>();
            var user = new UserViewModel();
            var userfam = new UserViewModel();

            //grabs the signed in user
            int userid = Convert.ToInt32(Session["userid"]);
            userfam = userfam.joinUserFamily(userid);
            int? familyid = userfam.user.FAMILY_ID;

            //lists only memebers of your family
            fam = user.getfamily(familyid);
            return View(fam);
        }

        public ActionResult AddFamilyMem()
        {
            
            string un = Request["email"];
            string password = Request["password"];
            string confirmpassword = Request["confirm"];
            string fname = Request["firstName"];
            string lname = Request["lastName"];
            string phone = Request["phoneNumber"];
            phone = new String(phone.Where(Char.IsDigit).ToArray());
            bool isgoodphone = false;
            bool isvalidemail = false;
            bool ispwsame = false;
            bool arenamesgood = false;
            var emailcheck = new Helpers.RegexUtilities();
           
            var userVM = new UserViewModel();
            var userJoin = new UserViewModel();
            var userfam = new UserViewModel();

            //current user
            int userid = Convert.ToInt32(Session["userid"]);

          
            //associate user with family
            userfam = userfam.joinUserFamily(userid);
            int? familyid = userfam.user.FAMILY_ID;
           

            userJoin = userJoin.joinUserFamily(familyid);
            
           
            var nametest = new UserViewModel();
            /*******************************************
                        Validation
            ********************************************/
            //check email format
            bool goodemailformat = emailcheck.IsValidEmail(un);
            if (password == confirmpassword)
            {
                ispwsame = true;
            }
            //checks for 25 because username is varchar 25, email is used for un and email
            if (!String.IsNullOrEmpty(un) && goodemailformat && un.Length <= 25)
            {

                isvalidemail = true;
            }

            if (!String.IsNullOrEmpty(lname) && !String.IsNullOrEmpty(fname) && lname.Length <=25 && fname.Length <= 25) {
                arenamesgood = true;
            }  
            if(phone.Length >=10 && phone.Length <= 32)
            {
                isgoodphone = true;
            }
            string pw = Helpers.UserHelper.getPasswordSaltHash(Request["password"]);
            using (var db = new Models.fclick_dbEntities())
            {
                //check if username is avaialable 
                // isgoodname = nametest.isAvailableUsername(un);
                if (ispwsame && arenamesgood && isvalidemail && isgoodphone)
                {


                    var user = new USER
                    {

                        USERNAME = Request["email"],
                        PASSWORD = pw,
                        //add family id write query join with user
                        STATUS = "Active",
                        CREATED_DATE = Helpers.createDate.getCreateDate(),
                        LAST_MOD_DATE = Helpers.createDate.getCreateDate(),
                        FAMILY_ID = userfam.user.FAMILY_ID,


                    };
                    db.USERs.Add(user);
                    db.SaveChanges();
                    

                    var userSignUp = new USER_CONTACT
                    {
                        USER_ID = user.USER_ID,
                        FIRST_NAME = Request["firstName"],
                        LAST_NAME = Request["lastName"],
                        EMAIL = Request["email"],
                        PHONE = phone,
                        //CARRIER =  NOT sure how to grab carrier?
                        CREATED_DATE = Helpers.createDate.getCreateDate(),
                        LAST_MOD_DATE = Helpers.createDate.getCreateDate(),

                    };
                    db.USER_CONTACT.Add(userSignUp);
                    db.SaveChanges();


                    var role = new USER_ROLE
                    {
                        ROLE_NAME = "user",
                        //setting active for testing 
                        STATUS = "Active",
                        CREATED_DATE = Helpers.createDate.getCreateDate(),
                        LAST_MOD_DATE = Helpers.createDate.getCreateDate(),
                        USER_ID = user.USER_ID,
                        ORG_ID = 1,

                    };
                    db.USER_ROLE.Add(role);
                    db.SaveChanges();
                }
                else
                {
                    if (!ispwsame)
                    {
                        ViewBag.Message = "Passwords do not match";
                        return RedirectToAction("AddFamily", "User");
                    }
                    else if (!arenamesgood)
                    {
                        ViewBag.Message = "First name and last name are required";
                        return RedirectToAction("AddFamily", "User");
                    }
                    else if (!isvalidemail)
                    {
                        ViewBag.Message = "Email format is not correct (e.g user@mail.com)";
                        return RedirectToAction("AddFamily", "User");
                    }
                    else if (!isgoodphone)
                    {
                        ViewBag.Message = "Phone number ";
                        return RedirectToAction("AddFamily", "User");
                    }
                    else {
                        ViewBag.Message = "Username is already in use";
                        return RedirectToAction("AddFamily", "User");
                    }
                }
            }

            //viewbag.message here

            return RedirectToAction("AddFamily", "User");
        }

        public ActionResult Edit()
        {
            var user = new UserViewModel();
            string phone = Request["newphone"];
            string confirmPhone = Request["confirmnewphone"];
            bool isgoodphone = false;
            string firstName = Request["newfirst"];
            string lastName = Request["newLast"];
            string email = Request["newemail"];
            string confirmEmail = Request["confirmnewemail"];
            bool isgoodemail = false;
            bool isemailavailable = false;
            string password = Request["newpassword"];
            string confirmPassword = Request["confirmnewpassword"];
            bool isgoodpw = false;
            string carrier = "";
            int userid = Convert.ToInt32(Session["userid"]);
            string msg = null;
            var emailcheck = new Helpers.RegexUtilities();
            bool goodemailformat = emailcheck.IsValidEmail(email);

            if ((String.IsNullOrEmpty(phone) || phone == confirmPhone)  || (phone.Length >= 10 && phone.Length <= 32))
            {
                isgoodphone = true;
            }
            else if(phone != confirmPhone)
            {
                msg = "Phone numbers do not match";
                return RedirectToAction("AccountManage", "User", new { errmsg = msg });
            }
            if ((email == confirmEmail || String.IsNullOrEmpty(email)) || goodemailformat)
            {
                isgoodemail = true;

            }
            else if(email != confirmEmail)
            {
                msg = "Emails do not match";
                return RedirectToAction("AccountManage", "User", new { errmsg = msg });
            }

            if (password == confirmPassword || String.IsNullOrEmpty(password))
            {
                isgoodpw = true;

            }
            else if(password != confirmPassword)
            {
                msg = "Passwords do not match";
                return RedirectToAction("AccountManage", "User", new { errmsg = msg});
            }

            isemailavailable = user.isAvailableUsername(email);

            if (!isemailavailable && !isgoodemail)
            {
                msg = "Email address is already in use";
                return RedirectToAction("AccountManage", "User", new { errmsg = msg });
            }

             if (isgoodpw && isgoodphone && isgoodemail ) {
                                

                user.UpdateUserInfo(userid, email, phone, carrier, firstName, lastName, password);
                msg = "Field Updated";
                return RedirectToAction("AccountManage", "User", new { errmsg = msg });
            }
            else
            {
                msg = "Name entered was too long";
                return RedirectToAction("AccountManage", "User", new { errmsg = msg });
            }
        }

        public ActionResult Delete(int id)
        {
            var user = new UserViewModel();
           
            user = user.getUser(id.ToString());
            ViewBag.Message = user.RemoveUser(user.user);

            return RedirectToAction("AddFamily", "User");
        }


        } // <end of class

      


    }
